package wci.intermediate.symtabimpl;

import java.util.ArrayList;

import wci.intermediate.*;

/**
 * <h1>SymTabStack</h1>
 *
 * <p>符号表栈的实现</p>
 *
 * <p>Copyright (c) 2009 by Ronald Mak</p>
 * <p>For instructional purposes only.  No warranties.</p>
 */
public class SymTabStackImpl
    extends ArrayList<SymTab>
    implements SymTabStack
{
	private static final long serialVersionUID = -6353713712087666465L;
	private int currentNestingLevel;  // 当前嵌套，默认为全局的0
	//主程序标识符的符号表项
	private SymTabEntry programId; 
    public SymTabStackImpl()
    {
        this.currentNestingLevel = 0;
        add(SymTabFactory.createSymTab(currentNestingLevel));
    }
    public int getCurrentNestingLevel()
    {
        return currentNestingLevel;
    }

    public SymTab getLocalSymTab()
    {
        return get(currentNestingLevel);
    }
    public SymTabEntry enterLocal(String name)
    {
        return get(currentNestingLevel).enter(name);
    }
    public SymTabEntry lookupLocal(String name)
    {
        return get(currentNestingLevel).lookup(name);
    }
    public SymTabEntry lookup(String name)
    {
    	 SymTabEntry foundEntry = null;
         // 搜索当前及更高层级（父层级)
         for (int i = currentNestingLevel; (i >= 0) && (foundEntry == null); --i)
         {
             foundEntry = get(i).lookup(name);
         }

         return foundEntry;
    }
    @Override
    public SymTabEntry getProgramId() {
    	return this.programId;
    }
    @Override
    public void setProgramId(SymTabEntry entry) {
    	this.programId = entry;    	
    }
    public SymTab push()
    {
        SymTab symTab = SymTabFactory.createSymTab(++currentNestingLevel);
        add(symTab);

        return symTab;
    }
    public SymTab push(SymTab symTab)
    {
        ++currentNestingLevel;
        add(symTab);

        return symTab;
    }
    public SymTab pop()
    {
        SymTab symTab = get(currentNestingLevel);
        remove(currentNestingLevel--);

        return symTab;
    }
}
